//
//  CardSerialize.m
//  MagicCardDemo
//
//  Created by 向恒 on 15/7/5.
//  Copyright (c) 2015年 向恒. All rights reserved.
//

#import "CardSerialize.h"

@implementation CardData (CardSerialize)

+(void)WriteData:(CardQueue *)Queue toFile:(NSString *)filename
{
    //下面的方法可以在模拟器中归档，真机中不行
    //NSString* strHomeDir = NSHomeDirectory();
    //NSString* strHomePath = [strHomeDir stringByAppendingPathComponent:@"magicm.archive"];
//    NSFileManager* fm = [NSFileManager defaultManager];
//    if(![fm fileExistsAtPath:strHomeDir isDirectory:YES])
//    {
//        NSLog(@"dir no exist!");
//    }
    
    //注意是：NSDocumentDirectory参数，别搞成NSDocumentationDirectory
    //搞错过，比较蛋疼。
    NSArray* doc = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString* docPath = [doc objectAtIndex:0];
    NSString* docLocation = [docPath stringByAppendingPathComponent:filename];
    
    NSFileManager* fm = [NSFileManager defaultManager];
    if(![fm fileExistsAtPath:docLocation isDirectory:NO])
    {
        [fm createFileAtPath:docLocation contents:nil attributes:nil];
    }
    
    
    //if(![NSKeyedArchiver archiveRootObject:Queue toFile:strHomePath])
    if(![NSKeyedArchiver archiveRootObject:Queue toFile:docLocation])
    {
        NSLog(@"data archive failed!");
    }
}

+(CardQueue*)ReadDataFromFile:(NSString *)filename
{
    //下面的方法可以在模拟器中解档，真机中不行
    //NSString* strHomeDir = NSHomeDirectory();
    //NSString* strHomePath = [strHomeDir stringByAppendingPathComponent:@"magicm.archive"];
    
    
    NSArray* doc = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString* docPath = [doc objectAtIndex:0];
    NSString* docLocation = [docPath stringByAppendingPathComponent:filename];

    NSFileManager* fm = [NSFileManager defaultManager];
    if(![fm fileExistsAtPath:docLocation isDirectory:NO])
    {
        //[fm createFileAtPath:docLocation contents:nil attributes:nil];
        NSLog(@"file not exist ,unarchive may failed.");
    }
    
    CardQueue* q =(CardQueue*)[NSKeyedUnarchiver unarchiveObjectWithFile:docLocation];
    return q;
}

@end